package com.example.safelib.fragment


import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.CustomListener
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.example.baselib.fragment.BaseFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.baselib.dialog.MsgDialog
import com.example.safelib.R
import com.example.safelib.SafeViewModel
import com.example.safelib.adapter.AddSenAdapter
import com.example.safelib.adapter.SafeLineAdapter
import com.tencent.bugly.beta.tinker.TinkerManager.getApplication
import kotlinx.android.synthetic.main.fragment_safe_line.*

import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * A simple [Fragment] subclass.
 */
class SafeLineFragment : BaseFragment<SafeViewModel>() {
    private lateinit var pvSensor: OptionsPickerView<Any>
    private lateinit var pvStartTime: TimePickerView
    private lateinit var pvEndTime: TimePickerView
    private var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    private val startTime: Calendar = Calendar.getInstance()
    private val endTime: Calendar = Calendar.getInstance()
    private var sensorName: String = ""
    private var sensorNo: String = ""
    private lateinit var senNameList: ArrayList<String>
    private lateinit var senNumList: List<List<String>>
    private val senAdapter: AddSenAdapter by lazy {
        AddSenAdapter(
            R.layout.line_sensor_item,
            viewModel.lineInfoList
        )
    }
    private val safeLineAdapter: SafeLineAdapter by lazy {
        SafeLineAdapter(
            activity!!.applicationContext,
            R.layout.safe_linechart_item,
            viewModel.lineDataList
        )
    }
    private var isOk = false
    override fun providerVMClass(): Class<SafeViewModel>? {
        return SafeViewModel::class.java
    }

    override fun contentLayout(): Int {
        return R.layout.fragment_safe_line
    }

    override fun initView() {
        initNickPicker()
        initTimeStartPicker()
        initTimeEndPicker()
        safe_line_sensor.setOnClickListener { pvSensor.show() }
        safe_line_sen_rcy.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        safe_line_sen_rcy.adapter = senAdapter
        senAdapter.setOnItemClickListener { adapter, view, position ->
            adapter.remove(position)
            safeLineAdapter.remove(position)
        }
        val empty = LayoutInflater.from(context).inflate(R.layout.line_empty_item, null, false)
        safeLineAdapter.emptyView = empty
        safe_line_chart_rcy.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        safe_line_chart_rcy.adapter = safeLineAdapter
    }

    override fun initData() {
        viewModel.getSenList().observe(this, Observer {
            senNameList=ArrayList<String>()
            for (sename in it.senname){
                    senNameList.add(sename.sensorname)
            }
            senNumList = it.senno
            pvSensor.setPicker(senNameList as List<String>, senNumList)//添加数据源
            isOk = true
        })
        viewModel.getLineChartData().observe(this, Observer {
            Log.i("++++++++", it.lineInfo.sensornum)
            if (it.lineValue.isNullOrEmpty())
                Toast.makeText(this.context, "相关传感器无曲线数据", Toast.LENGTH_LONG).show()
            senAdapter.notifyDataSetChanged()
            safeLineAdapter.notifyDataSetChanged()
        })
        if (!viewModel.getUnitInfo().isNullOrEmpty()){
            safe_line_nickname.text=viewModel.getUnitInfo()["unitname"]
        }

    }

    /**
     * @Description: [初始化传感器选择器]
     * @Param:
     * @Return:
     */
    private fun initNickPicker() {
        pvSensor = OptionsPickerBuilder(context,
            OnOptionsSelectListener { options1, options2, options3, v ->
                try {
                    sensorName = senNameList[options1]
                    val list = senNumList[options1]
                    if (list.isNotEmpty()) {
                        sensorNo = list[options2]
                        if (sensorNo.isNotEmpty()) {
                            pvStartTime.setDate(startTime)
                            pvStartTime.show()
                            pvSensor.dismiss()
                        } else {
                            Toast.makeText(this.context, "请选择有效传感器编号", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        Toast.makeText(context, "请选择传感器编号", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: Exception) {
                    pvSensor.dismiss()
                }
            })
            .isDialog(true)
            .setContentTextSize(18)
            .setLayoutRes(R.layout.pickerview_custom_nick, CustomListener { v ->

                v.findViewById<TextView>(R.id.picker_title).text = "选择传感器"
                v.findViewById<Button>(R.id.finish_btn).setOnClickListener {
                    pvSensor.returnData()
                }
                v.findViewById<Button>(R.id.cancel_btn).setOnClickListener { pvSensor?.dismiss() }
            })
            .setTextColorCenter(resources.getColor(R.color.colorDBlue))
            .setItemVisibleCount(9)
            .setLineSpacingMultiplier(2.6.toFloat())
            .setBackgroundId(R.color.colorBlack)
            .build()

    }

    /**
     * @Description: [初始化时间选择器]
     * @Param:
     * @Return:
     */
    private fun initTimeStartPicker() {
        val startDate = Calendar.getInstance()
        startDate.add(Calendar.YEAR, -2)
        pvStartTime = TimePickerBuilder(context,
            OnTimeSelectListener { date, _ ->
                startTime.time = date
                if (startTime.before(Calendar.getInstance())) {
                    pvStartTime?.dismiss()
                    pvEndTime?.setDate(endTime)
                    pvEndTime?.show()
                } else Toast.makeText(context, "请选择有效时间", Toast.LENGTH_SHORT).show()


            })
            .setType(booleanArrayOf(true, true, true, true, false, false))//分别对应年月日时分秒，默认全部显示
            .isDialog(true)
            .setContentTextSize(14)
            .setLayoutRes(
                R.layout.pickerview_custom_time
            ) { v ->
                v?.findViewById<TextView>(R.id.time_title)?.text = "选择开始时间"

                v?.findViewById<Button>(R.id.finish_btn)?.setOnClickListener {
                    pvStartTime?.returnData()

                }
                v?.findViewById<Button>(R.id.cancel_btn)
                    ?.setOnClickListener { pvStartTime?.dismiss() }
            }
            .setTextColorCenter(resources.getColor(R.color.colorDBlue))
            .setItemVisibleCount(5)
            .setDate(startTime)
            .setRangDate(startDate, Calendar.getInstance())
            .setItemVisibleCount(9)
            .setLineSpacingMultiplier(2.6.toFloat())
            .setBackgroundId(R.color.colorBlack)
            .setLabel("", "", "", "", "", "")
            .isCenterLabel(false).build()

    }

    private fun initTimeEndPicker() {
        val startDate = Calendar.getInstance()
        startDate.add(Calendar.YEAR, -2)
        pvEndTime = TimePickerBuilder(context,
            OnTimeSelectListener { date, _ ->
                endTime.time = date
                if (endTime.after(startTime)) {
                    pvEndTime.dismiss()
                    loadLineChartData()
                } else {
                    pvEndTime.dismiss()
                    Toast.makeText(context, "时间间隔太短", Toast.LENGTH_SHORT).show()
                }

            })
            .setType(booleanArrayOf(true, true, true, true, false, false))//分别对应年月日时分秒，默认全部显示
            .isDialog(true)
            .setContentTextSize(14)
            .setLayoutRes(
                R.layout.pickerview_custom_time
            ) { v ->
                v?.findViewById<TextView>(R.id.time_title)?.text = "选择结束时间"

                v?.findViewById<Button>(R.id.finish_btn)?.setOnClickListener {
                    pvEndTime?.returnData()
                }
                v?.findViewById<Button>(R.id.cancel_btn)
                    ?.setOnClickListener { pvEndTime?.dismiss() }
            }
            .setTextColorCenter(resources.getColor(R.color.colorDBlue))
            .setItemVisibleCount(5)
            .setDate(endTime)
            .setRangDate(startDate, Calendar.getInstance())
            .setItemVisibleCount(9)
            .setLineSpacingMultiplier(2.6.toFloat())
            .setBackgroundId(R.color.colorBlack)
            .setLabel("", "", "", "", "", "")
            .isCenterLabel(false).build()
    }

    /**
     * 加载曲线数据
     */
    private fun loadLineChartData() {
        val map = HashMap<String, String>()
        map["sensornum"] = sensorNo
        map["starttime"] = sdf.format(startTime.time)
        map["endtime"] = sdf.format(endTime.time)
        viewModel.loadLineChart(map)
    }

    override fun requestError(it: Exception?) {
        super.requestError(it)
        if (isOk) {
            safe_line_empty.visibility = View.VISIBLE
            safe_line_empty.findViewById<TextView>(R.id.err_txt).text = "请求失败,请重新添加"
            safe_line_empty.findViewById<TextView>(R.id.err_msg).text = it?.message
           safe_line_empty.findViewById<Button>(R.id.err_rest_btn).visibility=View.INVISIBLE
//            MsgDialog("请求失败\n" + it?.message + "\n" + "").show(
//                activity!!.supportFragmentManager,
//                "LineChartError"
//            )
        } else {
            safe_line_empty.visibility = View.VISIBLE
            safe_line_empty.findViewById<TextView>(R.id.err_txt).text = "获取传感器信息失败"
            safe_line_empty.findViewById<TextView>(R.id.err_msg).text = it?.message
            safe_line_empty.findViewById<Button>(R.id.err_rest_btn)
                .setOnClickListener { viewModel.loadSenList() }
        }

    }

    override fun onStart() {
        super.onStart()
        viewModel.loadSenList()
    }

}
